package com.literature.threeGroup.controller;

import com.github.pagehelper.Page;
import com.literature.threeGroup.pojo.*;
import com.literature.threeGroup.service.ResourceMaintainService;
import com.literature.threeGroup.util.POIUtil;
import com.literature.threeGroup.util.PageResult;
import com.literature.threeGroup.util.Result;
import com.literature.threeGroup.util.StatusCode;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@CrossOrigin
public class ResourceMaintainController {
    @Autowired
    private ResourceMaintainService resourceMaintainService;
    //资源维护列表
    @RequestMapping(value = "list",method = RequestMethod.POST)
    public List finAll(){
        return resourceMaintainService.findAll();
    }


    @RequestMapping(value = "list1/{page}/{size}",method = RequestMethod.POST)
    public PageResult finAll1(@RequestBody ResourceInfo resourceInfo,@PathVariable("page")int page,@PathVariable("size")int size){
        Page<ResourceInfo> statusDselect = resourceMaintainService.findAll2(resourceInfo, page, size);
        long total = statusDselect.getTotal();
        List<ResourceInfo> result = statusDselect.getResult();
        return new PageResult(total,result);
    }
    //资源维护编辑回显
    @RequestMapping(value = "findById/{id}",method = RequestMethod.GET)
    public ResourceInfo findById(@PathVariable("id")String id){
        return resourceMaintainService.findById(id);
    }

    //资源维护审核列表
    public List findUpdateList(){
        return resourceMaintainService.findUpdateList();
    }

    @RequestMapping(value = "updateList/{pageNum}/{pageSize}",method = RequestMethod.POST)
    public Result findUpdateList(@RequestBody ResourceUpdate resourceUpdate, @PathVariable("pageNum")int pageNum, @PathVariable("pageSize")int pageSize){
        PageResult findallupdate=resourceMaintainService.findupdateList(resourceUpdate,pageNum,pageSize);
        return  new Result(true, StatusCode.OK,"查询成功",findallupdate);
    }

    @RequestMapping(value = "updateAdd",method = RequestMethod.POST)
    public void updateadd(@RequestBody ResourceUpdate resourceUpdate){
        resourceMaintainService.updateadd(resourceUpdate);
    }
    //订购信息维护列表
    @RequestMapping(value = "orderList",method = RequestMethod.POST)
    public List findOrderList(){
        return resourceMaintainService.findOrderList();
    }
    //订购信息维护列表分页模糊
    @RequestMapping(value = "orderList1/{pageNum}/{pageSize}",method = RequestMethod.POST)
    public Result findOrderList1(@RequestBody Order order,@PathVariable("pageNum")int pageNum,@PathVariable("pageSize")int pageSize){
        PageResult findallorder=resourceMaintainService.findOrderList1(order,pageNum,pageSize);
        return new Result(true,StatusCode.OK,"查询成功",findallorder);
    }

    //下拉框代理公司
    @RequestMapping(value = "findCompany",method = RequestMethod.GET)
    public List findCompany(){
        return resourceMaintainService.findCompany();
    }
    //回显订购信息
    @RequestMapping(value = "findOrderId/{id}",method = RequestMethod.GET)
    public Order findOrderId(@PathVariable("id")String id){
        return resourceMaintainService.findOrderId(id);
    }

    //编辑订购信息维护表
    @RequestMapping(value = "orderUpdate/{id}",method = RequestMethod.PUT)
    public void updateOrder(@PathVariable("id")String id,@RequestBody Order order){
        order.setId(id);
        resourceMaintainService.updateOrder(id);
    }

    //审核
    @RequestMapping(value = "findAuditId/{id}",method = RequestMethod.GET)
    public ResourceUpdate findAuditId(@PathVariable("id")String id){
        return   resourceMaintainService.findAuditId(id);
    }

    /**
     *
     * 导出订购维护数据
     * @param req
     * @param resp
     * @param type
     * @throws IOException
     */
    @RequestMapping(value = "listOutPutExcel1",method = RequestMethod.GET)
    public void export2(HttpServletRequest req, HttpServletResponse resp, String type) throws IOException {

        //列名
        List<String> headers = Arrays.asList("ID","题名","订购机制","订购年份","代理公司","支付金额","是否到货","预估金额","结算价格","补款金额","数据库支持","载体","订购类型","审核状态",
                "代理公司户号","经费支持","是否订到","外币价格","退款金额","开通范围","印本订购方式","创建日期");
        List<Map<String, String>> exportDatas = new ArrayList<Map<String, String>>();
        List<Order> orderProductAttrList = resourceMaintainService.findOrderList();


        //将查询结果，存放进列值
        for (Order order : orderProductAttrList) {
            Map<String,String> map=new HashMap<>();
            map.put("ID", order.getId());
            map.put("题名", order.getTitle());
            map.put("订购机制",order.getOrderOrganization());
            map.put("订购年份",order.getOrderYear());
            map.put("代理公司",order.getAgencyCompanyId());
            // map.put("支付金额",Orders.getPay());
            map.put("是否到货",order.getIsArrival());
            // map.put("预估金额",Orders.getEstimatedAmount());
            // map.put("结算价格",Orders.getSettlementPrice());
            //map.put("补款金额",Orders.getFillingMoney());
            map.put("数据库支持",order.getDatabaseSupport());
            map.put("载体",order.getCarrier());
            map.put("订购类型",order.getOrderType());
            map.put("审核状态",order.getReviewStatus());
            map.put("代理公司户号",order.getDoorNoId());
            map.put("经费支持",order.getFinancialSupportId());
            map.put("是否订到",order.getIsOrder());
            //map.put("外币价格",Orders.getForeignPrice());
            // map.put("退款金额",Orders.getReturnPrice());
            map.put("开通范围",order.getOpenRange());
            map.put("印本订购方式",order.getPrinterMethodId());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 =  format.format(order.getCreateDate());
            map.put("创建日期",format1);
            exportDatas.add(map);
        }
        //导出
        exportExcel(req,resp,headers,exportDatas);
    }

    public void exportExcel(HttpServletRequest req, HttpServletResponse resp, List<String> headers, List<Map<String, String>> exportDatas) throws IOException {
        // 创建一个工作薄
        SXSSFWorkbook wb = new SXSSFWorkbook();
        //创建sheet
        Sheet sh = wb.createSheet("订购信息");
        //设置表头字体
        Font headFont = wb.createFont();
        headFont.setFontName("宋体");
        headFont.setColor(HSSFColor.WHITE.index);
        headFont.setFontHeightInPoints((short) 10);// 字体大小
        headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗

        // 设置表头样式
        CellStyle headStyle = wb.createCellStyle();
        headStyle.setFont(headFont);
        headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        headStyle.setLocked(true);
        headStyle.setWrapText(true);// 自动换行
        headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        headStyle.setFillForegroundColor(HSSFColor.GREEN.index);

        // 设置普通单元格字体
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);

        // 设置普通单元格样式
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);// 上下居中
        style.setWrapText(true);
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        style.setBorderLeft((short) 1);
        style.setRightBorderColor(HSSFColor.BLACK.index);
        style.setBorderRight((short) 1);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体
        style.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色．
        style.setFillForegroundColor(HSSFColor.WHITE.index);// 设置单元格的背景颜色．

        //设置单位格样式为文本
        DataFormat dataFormat = wb.createDataFormat();
        style.setDataFormat(dataFormat.getFormat("@"));

        /**
         * 设置列名
         */
        Row sheetRow = sh.createRow(0);
        Cell cell = null;
        for (int i = 0; i < headers.size(); i++) {
            cell = sheetRow.createCell(i);
            cell.setCellValue(headers.get(i));
            cell.setCellStyle(headStyle);
        }

        /**
         * 设置列值
         */
        int rows = 1;
        for (Map<String, String> data : exportDatas) {
            Row row = sh.createRow(rows++);
            int initCellNo = 0;
            int titleSize = headers.size();
            for (int i = 0; i < titleSize; i++) {
                String key = headers.get(i);
                Object object = data.get(key);
                if (object == null) {
                    row.createCell(initCellNo).setCellValue("");
                } else {
                    row.createCell(initCellNo).setCellValue(String.valueOf(object));
                }
                initCellNo++;
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "订购信息" + sdf.format(new Date()) + ".xlsx";
        resp.setContentType("application/octet-stream;charset=utf-8");
        resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        ServletOutputStream out = resp.getOutputStream();
        wb.write(out);
        out.close();
    }

   /* @RequestMapping(value = "listOutPutExcel2",method = RequestMethod.GET)
    public void export3(HttpServletRequest request,HttpServletResponse response,String type1){
        List<String> headers1 = Arrays.asList("ID","题名");
        List<Map<String,String>> exportDatas1=new ArrayList<Map<String,String>>();
        List<ResourceUpdate> orderProductAttrList = resourceMaintainService.findUpdateList();

        for (ResourceUpdate rupdate : orderProductAttrList) {
            Map<String,String> map=new HashMap<>();
            map.put("ID",rupdate.getId());
            map.put("用户",rupdate.getTitle());
           *//* map.put("类型", log.getLogType());
            map.put("内容", log.getLogContent());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 =  format.format(log.getLogDate());
            map.put("时间", format1);
            map.put("IP", log.getLogIp());*//*
            exportDatas1.add(map);
        }
        //导出
        exportExcel1(request,response,headers1,exportDatas1);
    }

    private void exportExcel1(HttpServletRequest request, HttpServletResponse response, List<String> headers1, List<Map<String, String>> exportDatas1) {
    }*/

    /**
     * 导出资源维护审核信息
     * @param req
     * @param resp
     * @param type
     * @throws IOException
     */
    @RequestMapping(value = "listOutPutExcel2",method = RequestMethod.GET)
    public void export1(HttpServletRequest req, HttpServletResponse resp, String type) throws IOException {
        //列名
        List<String> headers = Arrays.asList("ID", "题名","其他题名","分辑名","印本ISSN","电子ISSN","印本isbn","电子isbn","订购号","种类","学科","出版社"
                ,"国别","出版年","创刊年","语种","出版频率","分类号","期刊URL地址","载体","文献类型","出版模式","出版状态","价格","币种","文献来源","单位","套题名");
        List<Map<String, String>> exportDatas = new ArrayList<Map<String, String>>();
        List<ResourceUpdate> orderProductAttrList = resourceMaintainService.findUpdateList();


        //将查询结果，存放进列值
        for (ResourceUpdate rupdate : orderProductAttrList) {
            Map<String,String> map=new HashMap<>();
            map.put("ID", rupdate.getId());
            map.put("题名", rupdate.getTitle());
            map.put("其他题名", rupdate.getOtherTitle());
            map.put("分辑名", rupdate.getSeriesTitle());
            map.put("印本ISSN", rupdate.getPissn());
            map.put("电子ISSN", rupdate.getEissn());
            map.put("印本isbn", rupdate.getPisbn());
            map.put("电子isbn", rupdate.getEisbn());
            map.put("订购号", rupdate.getOrderNumber());
            map.put("种类", rupdate.getKindId());
            map.put("学科", rupdate.getSubject());
            map.put("出版社", rupdate.getPublisher());
            map.put("国别", rupdate.getCountry());
            map.put("出版年", rupdate.getPubYear());
            map.put("创刊年", rupdate.getFoundedYear());
            map.put("语种", rupdate.getLanguage());
            map.put("出版频率", rupdate.getPubFeq());
            map.put("分类号", rupdate.getClassiNumber());
            map.put("期刊URL地址", rupdate.getUrl());
            map.put("载体", rupdate.getCarrier());
            map.put("文献类型", rupdate.getType());
            map.put("出版模式", rupdate.getPubPattern());
            map.put("出版状态", rupdate.getPubStatus());
            map.put("价格", rupdate.getPrice());
            map.put("币种", rupdate.getCurrency());
            map.put("文献来源", rupdate.getLiterature());
            map.put("单位", rupdate.getOrganName());
            map.put("套题名", rupdate.getCoverName());
            exportDatas.add(map);
        }
        //导出
        exportExcel1(req,resp,headers,exportDatas);
    }

    public void exportExcel1(HttpServletRequest req, HttpServletResponse resp, List<String> headers, List<Map<String, String>> exportDatas) throws IOException {
        // 创建一个工作薄
        SXSSFWorkbook wb = new SXSSFWorkbook();
        //创建sheet
        Sheet sh = wb.createSheet("资源维护审核");
        //设置表头字体
        Font headFont = wb.createFont();
        headFont.setFontName("宋体");
        headFont.setColor(HSSFColor.WHITE.index);
        headFont.setFontHeightInPoints((short) 10);// 字体大小
        headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗

        // 设置表头样式
        CellStyle headStyle = wb.createCellStyle();
        headStyle.setFont(headFont);
        headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        headStyle.setLocked(true);
        headStyle.setWrapText(true);// 自动换行
        headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        headStyle.setFillForegroundColor(HSSFColor.GREEN.index);

        // 设置普通单元格字体
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);

        // 设置普通单元格样式
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);// 上下居中
        style.setWrapText(true);
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        style.setBorderLeft((short) 1);
        style.setRightBorderColor(HSSFColor.BLACK.index);
        style.setBorderRight((short) 1);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体
        style.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色．
        style.setFillForegroundColor(HSSFColor.WHITE.index);// 设置单元格的背景颜色．

        //设置单位格样式为文本
        DataFormat dataFormat = wb.createDataFormat();
        style.setDataFormat(dataFormat.getFormat("@"));

        /**
         * 设置列名
         */
        Row sheetRow = sh.createRow(0);
        Cell cell = null;
        for (int i = 0; i < headers.size(); i++) {
            cell = sheetRow.createCell(i);
            cell.setCellValue(headers.get(i));
            cell.setCellStyle(headStyle);
        }

        /**
         * 设置列值
         */
        int rows = 1;
        for (Map<String, String> data : exportDatas) {
            Row row = sh.createRow(rows++);
            int initCellNo = 0;
            int titleSize = headers.size();
            for (int i = 0; i < titleSize; i++) {
                String key = headers.get(i);
                Object object = data.get(key);
                if (object == null) {
                    row.createCell(initCellNo).setCellValue("");
                } else {
                    row.createCell(initCellNo).setCellValue(String.valueOf(object));
                }
                initCellNo++;
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "维护审核数据" + sdf.format(new Date()) + ".xlsx";
        resp.setContentType("application/octet-stream;charset=utf-8");
        resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        ServletOutputStream out = resp.getOutputStream();
        wb.write(out);
        out.close();
    }

    /**
     * 资源信息维护数据
     * @param req
     * @param resp
     * @param type
     * @throws IOException
     */
    @RequestMapping(value = "listOutPutExcel3",method = RequestMethod.GET)
    public void export3(HttpServletRequest req, HttpServletResponse resp, String type)throws IOException{
        List<String> headers = Arrays.asList("ID", "题名","其他题名","分辑名","印本ISSN","电子ISSN","印本isbn","电子isbn","订购号","种类","学科","出版社"
                ,"国别","出版年","创刊年","语种","出版频率","分类号","期刊URL地址","载体","文献类型","出版模式","出版状态","价格","币种","文献来源");
        List<Map<String, String>> exportDatas = new ArrayList<Map<String, String>>();
        List<ResourceInfo> orderProductAttrList = resourceMaintainService.findAll();


        //将查询结果，存放进列值
        for (ResourceInfo ResourceInfo : orderProductAttrList) {
            Map<String,String> map=new HashMap<>();
            map.put("ID", ResourceInfo.getId());
            map.put("题名", ResourceInfo.getTitle());
            map.put("其他题名", ResourceInfo.getOtherTitle());
            map.put("分辑名", ResourceInfo.getSeriesTitle());
            map.put("印本ISSN", ResourceInfo.getPissn());
            map.put("电子ISSN", ResourceInfo.getEissn());
            map.put("印本isbn", ResourceInfo.getPisbn());
            map.put("电子isbn", ResourceInfo.getEisbn());
            map.put("订购号", ResourceInfo.getOrderNumber());
            map.put("种类", ResourceInfo.getKindId());
            map.put("学科", ResourceInfo.getSubject());
            map.put("出版社", ResourceInfo.getPublisher());
            map.put("国别", ResourceInfo.getCountry());
            map.put("出版年", ResourceInfo.getPubYear());
            map.put("创刊年", ResourceInfo.getFoundedYear());
            map.put("语种", ResourceInfo.getLanguage());
            map.put("出版频率", ResourceInfo.getPubFeq());
            map.put("分类号", ResourceInfo.getClassiNumber());
            map.put("期刊URL地址", ResourceInfo.getUrl());
            map.put("载体", ResourceInfo.getCarrier());
            map.put("文献类型", ResourceInfo.getType());
            map.put("出版模式", ResourceInfo.getPubPattern());
            map.put("出版状态", ResourceInfo.getPubStatus());
            map.put("价格", ResourceInfo.getPrice());
            map.put("币种", ResourceInfo.getCurrency());
            map.put("文献来源", ResourceInfo.getLiterature());
            exportDatas.add(map);
        }
        //导出
        exportExcel3(req,resp,headers,exportDatas);
    }
    public void exportExcel3(HttpServletRequest req, HttpServletResponse resp, List<String> headers, List<Map<String, String>> exportDatas) throws IOException {
        // 创建一个工作薄
        SXSSFWorkbook wb = new SXSSFWorkbook();
        //创建sheet
        Sheet sh = wb.createSheet("资源信息维护");
        //设置表头字体
        Font headFont = wb.createFont();
        headFont.setFontName("宋体");
        headFont.setColor(HSSFColor.WHITE.index);
        headFont.setFontHeightInPoints((short) 10);// 字体大小
        headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗

        // 设置表头样式
        CellStyle headStyle = wb.createCellStyle();
        headStyle.setFont(headFont);
        headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        headStyle.setLocked(true);
        headStyle.setWrapText(true);// 自动换行
        headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        headStyle.setFillForegroundColor(HSSFColor.GREEN.index);

        // 设置普通单元格字体
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);

        // 设置普通单元格样式
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);// 上下居中
        style.setWrapText(true);
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        style.setBorderLeft((short) 1);
        style.setRightBorderColor(HSSFColor.BLACK.index);
        style.setBorderRight((short) 1);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体
        style.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色．
        style.setFillForegroundColor(HSSFColor.WHITE.index);// 设置单元格的背景颜色．

        //设置单位格样式为文本
        DataFormat dataFormat = wb.createDataFormat();
        style.setDataFormat(dataFormat.getFormat("@"));

        /**
         * 设置列名
         */
        Row sheetRow = sh.createRow(0);
        Cell cell = null;
        for (int i = 0; i < headers.size(); i++) {
            cell = sheetRow.createCell(i);
            cell.setCellValue(headers.get(i));
            cell.setCellStyle(headStyle);
        }

        /**
         * 设置列值
         */
        int rows = 1;
        for (Map<String, String> data : exportDatas) {
            Row row = sh.createRow(rows++);
            int initCellNo = 0;
            int titleSize = headers.size();
            for (int i = 0; i < titleSize; i++) {
                String key = headers.get(i);
                Object object = data.get(key);
                if (object == null) {
                    row.createCell(initCellNo).setCellValue("");
                } else {
                    row.createCell(initCellNo).setCellValue(String.valueOf(object));
                }
                initCellNo++;
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "resourceInfo" +".xls";
        resp.setContentType("application/octet-stream;charset=utf-8");
        resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        ServletOutputStream out = resp.getOutputStream();
        wb.write(out);
        out.close();
    }

    @RequestMapping(value = "queryDevied",method = RequestMethod.GET)
    public Result queryDevied() throws Exception {
        List<ResourceInfo> list=resourceMaintainService.queryDevied();

        POIUtil.export(list);
        return new Result(true,"导出成功");
    }

    @RequestMapping(value = "importResource",method = RequestMethod.GET)
    public List<ResourceInfo> importResource(@RequestParam(value = "title",defaultValue = "")String title) throws Exception {
        if(POIUtil.importExcel()!=null){
            List<ResourceInfo> list=POIUtil.importExcel();
            return list;
        }else {
            return null;
        }
    }

    @RequestMapping("findResourceId/{id}")
    public ResourceInfo findResourceId(@PathVariable("id")String id){
        return resourceMaintainService.findResourceId(id);
    }

    @RequestMapping("findresourceupId/{id}")
    public ResourceUpdate findResourceupId(@PathVariable("id")String id){
        return resourceMaintainService.findResourceupId(id);
    }


}
